﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Telerik.WinControls.UI;

using SharpPcap;
using SharpPcap.WinPcap;

using System.Threading;

using PersianProxy.Common.Library;

namespace PersianProxy.Clients.Windows
{
    public partial class rrfMain : Telerik.WinControls.UI.RadRibbonForm
    {
        public rrfMain()
        {
            InitializeComponent();
        }

        private void rrfMain_Load(object sender, EventArgs e)
        {
            LoadNetworkAdapters();
            StartSockServer();
        }


        #region Network Adapters Tab

        private void LoadNetworkAdapters()
        {
            foreach (var dev in CaptureDeviceList.Instance)
            {
                ListViewDataItem lvdi = new ListViewDataItem();
                lvdi.Text = (dev as WinPcapDevice).Interface.FriendlyName;
                lvdi.Tag = dev.Name;

                rlvNetworkAdapters.Items.Add(lvdi);
            }
        }

        private void rlvNetworkAdapters_ItemCheckedChanged(object sender, Telerik.WinControls.UI.ListViewItemEventArgs e)
        {
            
            if (e.Item.CheckState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                NetworkAdapter = CaptureDeviceList.Instance[e.Item.Tag.ToString()];
                rlvNetworkAdapters.Enabled = false;

                StartCapture();
            }

        }

        private void rlvNetworkAdapters_SelectedItemChanged(object sender, EventArgs e)
        {
            rbeStart.Enabled = true;
        }

        private void rbeStart_Click(object sender, EventArgs e)
        {
            StartCapture();

            rbeStart.Enabled = !rbeStart.Enabled;
            rbeStop.Enabled = !rbeStop.Enabled;
        }

        private void rbeStop_Click(object sender, EventArgs e)
        {
            rbeStart.Enabled = !rbeStart.Enabled;
            rbeStop.Enabled = !rbeStop.Enabled;
        }

        #endregion

        #region Network Adapter

        private bool BackgroundThreadStop;
        private object QueueLock = new object();
        private List<RawCapture> PacketQueue = new List<RawCapture>();
        private DateTime LastStatisticsOutput;
        private TimeSpan LastStatisticsInterval = new TimeSpan(0, 0, 2);
        private System.Threading.Thread backgroundThread;
        private int packetCount;
        private ICaptureStatistics captureStatistics;
        private bool statisticsUiNeedsUpdate = false;
        ICaptureDevice NetworkAdapter;

        void StartCapture()
        {
            //packetCount = 0;
            //packetStrings = new Queue<PacketWrapper>();
            //bs = new BindingSource();
            //dataGridView.DataSource = bs;
            //LastStatisticsOutput = DateTime.Now;

            // start the background thread
            //BackgroundThreadStop = false;
            //backgroundThread = new System.Threading.Thread(BackgroundThread);
            //backgroundThread.Start();

            NetworkAdapter = CaptureDeviceList.Instance[rlvNetworkAdapters.SelectedItem.Tag.ToString()];

            NetworkAdapter.OnPacketArrival += NetworkAdapter_OnPacketArrival;
            NetworkAdapter.OnCaptureStopped += NetworkAdapter_OnCaptureStopped;

            NetworkAdapter.Open();
            NetworkAdapter.StartCapture();

            //NetworkAdapter.Capture();

        }

        void NetworkAdapter_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var time = e.Packet.Timeval.Date;
            var len = e.Packet.Data.Length;

            var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

            
            var tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packet);
            if (tcpPacket != null)
            {
                var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket;
                System.Net.IPAddress srcIp = ipPacket.SourceAddress;
                System.Net.IPAddress dstIp = ipPacket.DestinationAddress;
                int srcPort = tcpPacket.SourcePort;
                int dstPort = tcpPacket.DestinationPort;

                RadListDataItem rldi = new RadListDataItem();
                rldi.Text = srcIp + ":" + srcPort + "->" + dstIp + ":" + dstPort;
                rlcPackets.Items.Add(rldi);

            }

        }

        void NetworkAdapter_OnCaptureStopped(object sender, CaptureStoppedEventStatus status)
        {

        }

        void StopCapture()
        {

        }

        #endregion

        #region Proxy

        void StartSockServer()
        {
            Fiddler.CONFIG.bCaptureCONNECT = true;


            Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
            Fiddler.FiddlerApplication.OnNotification += FiddlerApplication_OnNotification;
            Fiddler.FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
            Fiddler.FiddlerApplication.OnWebSocketMessage += FiddlerApplication_OnWebSocketMessage;
            Fiddler.FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
            
            Fiddler.FiddlerApplication.Startup(8888,false,false);

        }

        void FiddlerApplication_OnNotification(object sender, Fiddler.NotificationEventArgs e)
        {
            int x = 0;
        }

        void FiddlerApplication_AfterSessionComplete(Fiddler.Session oSession)
        {
            int x = 0;
        }

        void FiddlerApplication_OnWebSocketMessage(object sender, Fiddler.WebSocketMessageEventArgs e)
        {
            int x = 0;
        }

        void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
        {
            if(oSession.RequestMethod!="CONNECT")
                oSession.url = "p.hmsvisa.com/" + Security.EncodeChars(oSession.url);
            //oSession.url = "p.hmsvisa.com/" + Security.EncodeChars("apis.google.com/js/plusone.js");
        }

        void FiddlerApplication_BeforeResponse(Fiddler.Session oSession)
        {

            ShowProxyActivity(oSession);
            
        }

        private void ShowProxyActivity(Fiddler.Session oSession)
        {
            RadListDataItem rldi = new RadListDataItem();
            rldi.Text = oSession.fullUrl;
            rlcProxy.Items.Insert(0, rldi);
        }

        void StopSocksServer()
        {
        }

        #endregion


    }
}
